package K8sProxy

import (
	"errors"
	v1 "gitee/kubehark/kubehark-operator/api/kubehark/v1"
	restclient "k8s.io/client-go/rest"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/kubectl/pkg/proxy"
	"kubehark/kubehark-framwork/pkg/Data/DataSourceCrd"
	"net/http"
	"sync"
	"time"
)

var ClusterProxyMap sync.Map

type ClusterClientAuth struct {
	Name             string
	RestClientConfig *restclient.Config
	proxy            http.Handler
}

// Do comment
func (t *ClusterClientAuth) DoHttpProxy(res http.ResponseWriter, req *http.Request, path string) {
	req.URL.Path = path
	req.Header.Del("Authorization")
	if t.proxy == nil {
		//t.initProxy()
		t.proxy, _ = proxy.NewProxyHandler("/", nil, t.RestClientConfig, 30*time.Second)
	}
	t.proxy.ServeHTTP(res, req)
}

func GetProxyInfo(cluster string) (t *ClusterClientAuth, err error) {
	var (
		cacheToken interface{}
		ok         bool
	)
	cacheToken, ok = ClusterProxyMap.Load(cluster)
	if !ok {
		data, ok, err := DataSourceCrd.GetDataFromInformer(DataSourceCrd.Credential, cluster)
		if err != nil {
			return nil, err
		}
		if !ok{
			return nil,errors.New("not found cluster")
		}
		config, err := clientcmd.RESTConfigFromKubeConfig([]byte(data.(*v1.Credential).Spec.Kubeconfig))
		t = &ClusterClientAuth{
			Name:             cluster,
			RestClientConfig: config,
		}
		ClusterProxyMap.Store(cluster, t)
	}else {
		t = cacheToken.(*ClusterClientAuth)
	}
	return t,err

}
